package framework.snowflake;

import framework.runtime.SystemContext;
import framework.utils.ConvertUtil;
import framework.utils.EnvUtil;

/**
 * ENV:
 *   SNOWFLAKE_WORKER
 *   SNOWFLAKE_CENTER
 *   SNOWFLAKE_LENGTH 16/19
 */
public class Snowflake {

    private static NextId worker;

    static {
        Long workerId = 0L;
        Long datacenterId = 0L;
        Long length = 0L;

//        String w = EnvUtil.env("SNOWFLAKE_WORKER");
//        String d = EnvUtil.env("SNOWFLAKE_CENTER");
//        String l = EnvUtil.env("SNOWFLAKE_LENGTH");
//
//        workerId = ConvertUtil.toLong(w);
//        datacenterId = ConvertUtil.toLong(d);
//        length = ConvertUtil.toLong(l);

        try {
            SnowflakeConfig snowflakeConfig = SystemContext.getBean(SnowflakeConfig.class);
            workerId = snowflakeConfig.getWorker();
            datacenterId = snowflakeConfig.getCenter();
            length = snowflakeConfig.getLength();
        } catch (NullPointerException exception) {
            String w = EnvUtil.env("SNOWFLAKE_WORKER");
            String d = EnvUtil.env("SNOWFLAKE_CENTER");
            String l = EnvUtil.env("SNOWFLAKE_LENGTH");
            //
            workerId = ConvertUtil.toLong(w);
            datacenterId = ConvertUtil.toLong(d);
            length = ConvertUtil.toLong(l);
        }

        //
        if (length == 19)
            worker = new SnowflakeWorker(workerId, datacenterId);
        else
            worker = new Snowflake16(workerId, datacenterId);
    }

    /**
     * 获取下一个ID
     *
     * @return
     */
    public static long nextId() {
        long id = worker.nextId();
        return id;
    }

}
